//
//  BreakPointDownload.m
//  Duandianxiazai
//
//  Created by qianfeng on 15/10/16.
//  Copyright (c) 2015年 Lskang. All rights reserved.
//

#import "BreakPointDownload.h"

@implementation BreakPointDownload

- (void)breakPointDownLoadDataWithUrl:(NSString *)url downloadProcess:(downloadBlock)myBlock{
    self.myBlock = myBlock;
    
    NSString *filePath = [self getFullFilePathWithUrl:url];
    
    BOOL isExiste = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    
    if (!isExiste) {
        self.loadedSize = 0;
        //没有 创建文件
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    }else{
        //有 要获取已经下载的文件大小
        NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
        self.loadedSize = fileDict.fileSize;
    }
    
    //打开文
    self.fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    
    //发送下载请求
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    //断点下载 应该告诉 服务器从那一字节开始下载
    //通过请求头 发给服务器
    
    [request addValue:[NSString stringWithFormat:@"bytes=%llu-",self.loadedSize] forHTTPHeaderField:@"Range"];
    
    //启动一个线程 进行请求下载
    
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

#pragma mark - NSURLConnectionDataDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    //服务器告诉客户端 要发数据了  还会告诉发送的大小
    NSLog(@"len:%llu",response.expectedContentLength);
    //计算文件总大小
    self.fileSize = self.loadedSize+response.expectedContentLength;
    
}
// 服务器发送数据的时候 回调
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    //下载过程 将data写到本地沙盒
    [self.fileHandle seekToEndOfFile];
    [self.fileHandle writeData:data];
    [self.fileHandle synchronizeFile]; //同步到磁盘
    //文件 已经下载大小
    self.loadedSize += data.length;
    
    if (self.myBlock) {
        self.myBlock(self);
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    [self stopDownload];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    [self stopDownload];
}

- (void)stopDownload{
    if (self.connection) {
        [self.connection cancel];
        self.connection = nil;
    }
    [self.fileHandle closeFile];
}


- (NSString *)getFullFilePathWithUrl:(NSString *)urlname{
//    NSString *name = [urlname MD5Hash];
    //获取在沙盒中得路径
    NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",urlname];
    
    //NSString *path = [NSString stringWithFormat:@"/Users/qianfeng123/Desktop/456789/%@",name];
    
    return path;
}





@end
